package com.im.service.tenderInfo.smo;

import com.im.MDA;
import com.im.service.bidInfo.dao.IBidInfoOperDAO;
import com.im.service.bidInfo.smo.IBidInfoOperSMO;
import com.im.service.bidInfo.smo.IBidInfoQuerySMO;
import com.im.service.docManage.dao.IDocManageQueryDAO;
import com.im.service.docManage.smo.IDocManageOperSMO;
import com.im.service.docManage.smo.IDocManageQuerySMO;
import com.im.service.dto.*;
import com.im.service.evalBidParty.smo.IEvalBidPartyOperSMO;
import com.im.service.evalBidParty.smo.IEvalBidPartyQuerySMO;
import com.im.service.projectInfo.dao.IFundSourceQueryDAO;
import com.im.service.purchasePlan.smo.IPurchasePlanOperSMO;
import com.im.service.purchasePlan.smo.IPurchasePlanQuerySMO;
import com.im.service.result.smo.IResultOperSMO;
import com.im.service.result.smo.IResultQuerySMO;
import com.im.service.tenderInfo.dao.ITenderInfoOperDAO;
import com.im.service.tenderInfo.dao.ITenderInfoQueryDAO;
import com.im.util.DateUtil;
import com.im.util.ListUtil;
import com.im.util.StringUtil;
import com.im.viewmodel.projectInvitManage.InvitInfoManageOperReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.Bidi;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.*;

@Service
public class TenderInfoOperSMOImpl implements ITenderInfoOperSMO {

    @Autowired
    private ITenderInfoOperDAO tenderInfoOperDAO;
    @Autowired
    private ITenderInfoQueryDAO tenderInfoQueryDAO;
    @Autowired
    private IBidInfoOperSMO bidInfoOperSMO;
    @Autowired
    private IEvalBidPartyOperSMO evalBidPartyOperSMO;
    @Autowired
    private IEvalBidPartyQuerySMO evalBidPartyQuerySMO;
    @Autowired
    private IResultOperSMO resultOperSMO;
    @Autowired
    private IPurchasePlanQuerySMO purchasePlanQuerySMO;
    @Autowired
    private IPurchasePlanOperSMO purchasePlanOperSMO;
    @Autowired
    private IResultQuerySMO resultQuerySMO;
    @Autowired
    private IDocManageOperSMO docManageOperSMO;
    @Autowired
    private IFundSourceQueryDAO fundSourceQueryDAO;
    @Autowired
    private IDocManageQuerySMO docManageQuerySMO;
    @Autowired
    private IBidInfoQuerySMO bidInfoQuerySMO;

    @Override
    public void saveResultInfo(InvitInfoManageOperReqVo reqVo) throws Exception {

        String remark = reqVo.getRemark();
        String tenderTitle = reqVo.getTenderTitle();
        String docManageName = reqVo.getDocManageName();
        // 90W一下可以没有 标书（docManage） 和 采购计划（purchPlan）
        String implProjId = reqVo.getImpleProjId();
        if(StringUtil.isEmpty(implProjId)){
            throw new BaseException("实施项目不能为空");
        }

        String statusCd = reqVo.getStatusCd();
        if(StringUtil.isEmpty(statusCd)){
            throw new BaseException("状态不能为空");
        }

        String openDt = reqVo.getOpenDt();
        if(openDt == null){
            throw new BaseException("开标时间不能为空");
        }
        Date openDate = DateUtil.getDateFromString(openDt,"yyyy-MM-dd");
        String purchPlanId = reqVo.getPurchPlanId();
        String docManageId = reqVo.getDocManageId();
        String evalPartyId = reqVo.getEvalPartyId();
        if(StringUtil.isEmpty(evalPartyId)){
            throw new BaseException("评标参与人不能为空");
        }

        // 查询项目是否大于90W
        if(isBigProject(implProjId)){
            if(StringUtil.isEmpty(purchPlanId)){
                throw new BaseException("采购计划不能为空");
            }
            if(StringUtil.isEmpty(docManageId)){
                throw new BaseException("标书不能为空");
            }
        }

        // 查询招标书是否存在
        Map<String,Object> inMap = new HashMap<String,Object>();
        inMap.put("impleProjId",implProjId);
        if(!StringUtil.isEmpty(purchPlanId)){
            inMap.put("purchPlanId",purchPlanId);
        }
        List<TenderInfo> tenderList = tenderInfoQueryDAO.queryTenderInfoList(inMap);
        String tendInfoId = "";
        if(!ListUtil.isListEmpty(tenderList)){
            TenderInfo tender = tenderList.get(0);
            TenderInfo tenderInfo = new TenderInfo();
            tenderInfo.setTenderInfoId(tender.getTenderInfoId());
            tenderInfo.setStatusCd(20);
            tenderInfoOperDAO.saveTenderInfo(tenderInfo);
        }else{
            // 招标书信息
            TenderInfo tenderInfo = new TenderInfo();
            tendInfoId  = UUID.randomUUID().toString();
            tenderInfo.setDocManageId("".equals(docManageId)?null:docManageId);
            tenderInfo.setImpleProjId(implProjId);
            tenderInfo.setPurchPlanId("".equals(purchPlanId)?null:purchPlanId);
            tenderInfo.setTenderInfoId(tendInfoId);
            tenderInfo.setTenderCode(tendInfoId);
            tenderInfo.setDescription(reqVo.getRemark());
            tenderInfo.setCreateDt(new Date());
            tenderInfo.setStatusCd(20);
            tenderInfo.setDescription(remark);
            tenderInfo.setTenderTitle(StringUtil.isEmpty(docManageName)?tenderTitle:docManageName);
            tenderInfoOperDAO.saveTenderInfo(tenderInfo);
        }

        // 更新文件管理 docManage
        if(!StringUtil.isEmpty(docManageId)){
            DocManage docManage = new DocManage();
            docManage.setDocManageId(docManageId);
            docManage.setRelaObjType(MDA.DOC_MANAGE_RELA_OBJ_TYPE_TENDER);
            docManage.setRelaObjId(tendInfoId);
            docManageOperSMO.updateDocManage(docManage);
        }

        // 投标书信息
        BidInfo bidInfo = new BidInfo();
        String bidInfoId = UUID.randomUUID().toString();
        bidInfo.setBidInfoId(bidInfoId);
        bidInfo.setBidInfoCode(bidInfoId);
        bidInfo.setTenderInfoId(tendInfoId);
        bidInfo.setStatusCd(Integer.valueOf(statusCd));
        bidInfo.setDescription(remark);
        bidInfoOperSMO.saveBidInfo(bidInfo);

        // 中标结果
        Result result = new Result();
        result.setBidInfoId(bidInfoId);
        result.setTenderInfoId(tendInfoId);
        String resultId = UUID.randomUUID().toString();
        result.setResultId(resultId);
        result.setCreateDt(new Date());
        result.setOpenDt(openDt);
        resultOperSMO.saveResult(result);

        // 评标参与人
        String[] epids = evalPartyId.split(",");
        for(int i=0;i<epids.length;i++){
            EvalBidParty evalBidParty = new EvalBidParty();
            evalBidParty.setBidPartyId(UUID.randomUUID().toString());
            evalBidParty.setResultId(resultId);
            evalBidParty.setReviewer(epids[i]);
            evalBidParty.setCreateDt(new Date());
            evalBidPartyOperSMO.saveEvalBidParty(evalBidParty);
        }
    }

    @Override
    public void saveTenderInfo(TenderInfo tenderInfo) {
        tenderInfoOperDAO.saveTenderInfo(tenderInfo);
    }

    @Override
    public void updateResultInfo(InvitInfoManageOperReqVo reqVo) throws Exception {
        String implProjId = reqVo.getImpleProjId();
        String purchPlanId = reqVo.getPurchPlanId();
        String docManageId = reqVo.getDocManageId();
        String evalPartyId = reqVo.getEvalPartyId();
        String openDt = reqVo.getOpenDt();
        String statusCd = reqVo.getStatusCd();
        String remark = reqVo.getRemark();
        if(StringUtil.isEmpty(implProjId)){
            throw new BaseException("实施项目不能为空");
        }
        if(StringUtil.isEmpty(evalPartyId)){
            throw new BaseException("评标参与人不能为空");
        }
        String tenderInfoId = reqVo.getTenderInfoId();
        if(StringUtil.isEmpty(tenderInfoId)){
            throw new BaseException("招标信息不能为空");
        }
        if(openDt == null){
            throw new BaseException("开标时间不能为空");
        }
        if(StringUtil.isEmpty(statusCd)){
            throw new BaseException("状态不能为空");
        }

        // 查询项目是否大于90W
        if(isBigProject(implProjId)){
            if(StringUtil.isEmpty(purchPlanId)){
                throw new BaseException("采购计划不能为空");
            }
            if(StringUtil.isEmpty(docManageId)){
                throw new BaseException("标书不能为空");
            }
        }

        Map<String,Object> inMap = new HashMap<String,Object>();

        // 根据实施项目ID查询采购计划
//        inMap.put("impleProjId",implProjId);
//        List<PurchasePlan> purchasePlanList = purchasePlanQuerySMO.queryPurchasePlanByParam(inMap);

//        if(!ListUtil.isListEmpty(purchasePlanList)){
//            // old
//            PurchasePlan pp = purchasePlanList.get(0);
//            pp.setImpleProjId(null);
//            purchasePlanOperSMO.updatePurchasePlanAll(pp);
//        }
        if(!StringUtil.isEmpty(purchPlanId)){
            // new
            PurchasePlan purchasePlan = new PurchasePlan();
            purchasePlan.setPurchPlanId(purchPlanId);
            PurchasePlan retP = purchasePlanQuerySMO.queryPurchasePlanDetail(purchasePlan);
            if(retP==null){
                throw new BaseException("查询采购计划为空");
            }
            retP.setImpleProjId(implProjId);
            retP.setStatusCd(Integer.valueOf(statusCd));
            purchasePlanOperSMO.updatePurchasePlan(retP);
        }

        // 更新 文件管理  docManage
        // 查询tenderInfo -- docManageId
        TenderInfo tenderInfo = tenderInfoQueryDAO.queryTenderInfoById(tenderInfoId);
        if(!StringUtil.isEmpty(tenderInfo.getDocManageId())){
            DocManage docManage = docManageQuerySMO.queryDocManageById(tenderInfo.getDocManageId());
            docManage.setRelaObjType(null);
            docManage.setRelaObjId(null);
            docManage.setVersion(new Date());
            docManageOperSMO.updateDocManageAll(docManage);
        }

        if(!StringUtil.isEmpty(docManageId)){
            DocManage docManage = docManageQuerySMO.queryDocManageById(docManageId);
            docManage.setRelaObjType(MDA.DOC_MANAGE_RELA_OBJ_TYPE_TENDER);
            docManage.setRelaObjId(tenderInfoId);
            docManage.setVersion(new Date());
            docManageOperSMO.updateDocManage(docManage);
        }

        // 更新 招标信息
        tenderInfo.setTenderInfoId(tenderInfoId);
        tenderInfo.setImpleProjId(implProjId);
        tenderInfo.setPurchPlanId(StringUtil.isEmpty(purchPlanId)?null:purchPlanId);
        tenderInfo.setDocManageId(StringUtil.isEmpty(docManageId)?null:docManageId);
        tenderInfo.setVersion(new Date());
        tenderInfo.setDescription(remark);
        tenderInfo.setStatusCd(Integer.valueOf(statusCd));
        tenderInfoOperDAO.updateTenderInfoAll(tenderInfo);

        // 投标书信息
        String bidInfoId = "";
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("tenderInfoId",tenderInfoId);
        List<BidInfo> bidInfos =  bidInfoQuerySMO.queryBidInfoList(param);
        if(!ListUtil.isListEmpty(bidInfos)){
            BidInfo bidInfo = bidInfos.get(0);
            bidInfoId = bidInfo.getBidInfoId();
            bidInfo.setStatusCd(Integer.valueOf(statusCd));
            bidInfoOperSMO.updateBidInfo(bidInfo);
        }else{
            BidInfo bidInfo = new BidInfo();
            bidInfoId = UUID.randomUUID().toString();
            bidInfo.setBidInfoId(bidInfoId);
            bidInfo.setBidInfoCode(bidInfoId);
            bidInfo.setTenderInfoId(tenderInfoId);
            bidInfo.setStatusCd(Integer.valueOf(statusCd));
            bidInfo.setDescription(remark);
            bidInfoOperSMO.saveBidInfo(bidInfo);
        }

        String resultId = "";
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("tenderInfoId",tenderInfoId);
        List<Result> results =  resultQuerySMO.queryResultList(paramMap);
        Boolean isExistsRst = false;
        if(!ListUtil.isListEmpty(results)){
            isExistsRst = true;
            Result result =results.get(0);
            resultId = results.get(0).getResultId();
            Date openDate = DateUtil.getDateFromString(openDt,"yyyy-MM-dd");
            result.setOpenDt(openDt);
            resultOperSMO.updateResult(result);
        }else{
            // 中标结果
            isExistsRst = false;
            Result result = new Result();
            result.setBidInfoId(bidInfoId);
            result.setTenderInfoId(tenderInfoId);
            resultId = UUID.randomUUID().toString();
            result.setResultId(resultId);
            result.setCreateDt(new Date());
            result.setOpenDt(openDt);
            resultOperSMO.saveResult(result);
        }

        // 评标参与人
        //如果已经有过开标记录，则先删除参与人再增加
        if (isExistsRst) {
            Map<String,Object> rstMap = new HashMap<String,Object>();
            rstMap.put("resultId",resultId);
            evalBidPartyOperSMO.deleteByResultId(rstMap);
        }

        String[] epids = evalPartyId.split(",");
        for(int i=0;i<epids.length;i++){
            EvalBidParty evalBidParty = new EvalBidParty();
            evalBidParty.setBidPartyId(UUID.randomUUID().toString());
            evalBidParty.setResultId(resultId);
            evalBidParty.setReviewer(epids[i]);
            evalBidParty.setCreateDt(new Date());
            evalBidPartyOperSMO.saveEvalBidParty(evalBidParty);
        }

        // 根据招标信息查询 中标结果
//        inMap.clear();
//        inMap.put("tenderInfoId",tenderInfoId);
//        List<Result> resultList = resultQuerySMO.queryResultList(inMap);
//        if(!ListUtil.isListEmpty(resultList)){
//            // 更新 中标结果 的 承接商
//            Result result = new Result();
//            result = resultList.get(0);
//            Date openDate = DateUtil.getDateFromString(openDt,"yyyy-MM-dd");
//            result.setOpenDt(openDt);
//            resultOperSMO.updateResult(result);
//
//            // 更新 投标书信息 的投标单位id
//            BidInfo bidInfo = new BidInfo();
//            bidInfo.setDescription(remark);
//            bidInfo.setBidInfoId(result.getBidInfoId());
//            bidInfoOperSMO.updateBidInfo(bidInfo);

//            if(!StringUtil.isEmpty(result.getResultId())){
//                inMap.clear();
//                inMap.put("resultId",result.getResultId());
//                evalBidPartyOperSMO.deleteByResultId(inMap);
//                String[] epids = evalPartyId.split(",");
//                for(int i=0;i<epids.length;i++){
//                    EvalBidParty evalBidParty = new EvalBidParty();
//                    evalBidParty.setBidPartyId(UUID.randomUUID().toString());
//                    evalBidParty.setResultId(result.getResultId());
//                    evalBidParty.setReviewer(epids[i]);
//                    evalBidParty.setCreateDt(new Date());
//                    evalBidPartyOperSMO.saveEvalBidParty(evalBidParty);
//                }
//            }
//        }
    }

    @Override
    public void updateTenderInfo(TenderInfo tenderInfo) {
        tenderInfoOperDAO.updateTenderInfo(tenderInfo);
    }

    @Override
    public void updateTenderInfoAll(TenderInfo tenderInfo) {
        tenderInfoOperDAO.updateTenderInfoAll(tenderInfo);
    }

    private boolean isBigProject(String impleProjId){
        // 查询项目是否大于90W
        FundSource fundSource = new FundSource();
        fundSource.setFundSourceObj(impleProjId);
        List<FundSource> fundSourceList = fundSourceQueryDAO.queryFoundSource(fundSource);
        float money =0;
        for(FundSource fs : fundSourceList){
            money = money + Float.valueOf(fs.getFundVal());
        }
        if(money > 90){
            return true;
        }
        return false;
    }


    @Override
    public void deleteResultInfo(InvitInfoManageOperReqVo reqVo) throws Exception {
        String tenderInfoId = reqVo.getTenderInfoId();
        if(StringUtil.isEmpty(tenderInfoId)){
            throw new BaseException("招标信息不能为空");
        }
        TenderInfo tenderInfo = tenderInfoQueryDAO.queryTenderInfoById(tenderInfoId);
        // 根据 resultId 删除 参与人表，再删除result表
        // 中标结果
        Map<String,Object> inMap = new HashMap<String,Object>();
        inMap.put("tenderInfoId", tenderInfoId);
        List<Result> retList = resultQuerySMO.queryResultList(inMap);
        if(!ListUtil.isListEmpty(retList)){
            for(Result rt : retList){
                // 评标参与人
                inMap.clear();
                inMap.put("resultId", rt.getResultId());
//                List<EvalBidParty> ebpList = evalBidPartyQuerySMO.queryEvalBidPartyList(inMap);
//                if(!ListUtil.isListEmpty(ebpList)){
//                    evalBidPartyOperSMO.deleteByResultId(inMap);
//                }
                evalBidPartyOperSMO.deleteByResultId(inMap);
                resultOperSMO.deleteResult(rt.getResultId());
            }
        }
        // 根据 招标信息表中的 内容 更新docManage 表，删除 bidInfo表
        if(tenderInfo!=null && !StringUtil.isEmpty(tenderInfo.getDocManageId())){
            DocManage docManage = docManageQuerySMO.queryDocManageById(tenderInfo.getDocManageId());
            if(docManage!=null){
                docManage.setRelaObjType(null);
                docManage.setRelaObjId(null);
                docManage.setVersion(new Date());
                docManageOperSMO.updateDocManageAll(docManage);
            }
        }

        inMap.clear();
        inMap.put("tenderInfoId", tenderInfoId);
        List<BidInfo> bidList = bidInfoQuerySMO.queryBidInfoList(inMap);
        if(!ListUtil.isListEmpty(bidList)){
            for(BidInfo bi : bidList){
                bidInfoOperSMO.deleteBidInfo(bi.getBidInfoId());
            }
        }
        tenderInfoOperDAO.deleteTenderInfo(tenderInfoId);
    }
}
